import axios from 'axios'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useMainStore } from '@/store'

const router = useRouter()

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = localStorage.getItem('token') || ''
    if(config.method === 'post') {
        let lang = localStorage.getItem('lang') || 'en'
        if(lang === 'cn') {
          lang = 'zh'
        }
        config.data.lang = lang
    }
    const mainStore = useMainStore()
    mainStore.setLoading(true)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const mainStore = useMainStore()
     mainStore.setLoading(false)
    // if the custom code is not 20000, it is judged as an error.
    if (res.type !== 'ok') {
      if(res.type == 999) {
        // 重新登录
        mainStore.setToken('')
        router.replace('/login')
      }
      message.error(res.message)
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res.message
    }
  },
  error => {
    const mainStore = useMainStore()
    mainStore.setLoading(false)
    console.log('err' + error) // for debug
     message.error(error.message)
    return Promise.reject(error)
  }
)

export default service
